﻿using System;
using System.IO;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace eBlog.Common
{

    /// <summary>
    /// 字符串处理类
    /// </summary>
    public class StringHelper
    {
        /// <summary>
        /// Texts to HTML.
        /// </summary>
        /// <param name="content">The TXT STR.</param>
        /// <returns>The formated str.</returns>
        public static string TextToHtml(string content)
        {
            StringBuilder sb = new StringBuilder(content);
            sb.Replace("&", "&amp;");
            sb.Replace("<", "&lt;");
            sb.Replace(">", "&gt;");
            sb.Replace("\"", "&quot;");
            //     sb.Replace("\'", "&#39;");
            sb.Replace(" ", "&nbsp;");
            sb.Replace("\t", "&nbsp;&nbsp;");
            sb.Replace("\r", "");
            sb.Replace("\n", "<br />");
            return sb.ToString();
            //  return ShitEncode(sb.ToString());

            //return content.Replace(" ", "&nbsp;").Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;").
            //    Replace("<", "&lt;").Replace(">", "&gt;").Replace("\r", "").Replace("\n", "<br />");
        }

        /// <summary>
        /// html to text
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string HtmlToText(string content)
        {
            StringBuilder sb = new StringBuilder(content);
            sb.Replace("<br />", "\n");
            sb.Replace("<br/>", "\n");
            //  sb.Replace("\r", "");
            sb.Replace("&nbsp;&nbsp;", "\t");
            sb.Replace("&nbsp;", " ");
            sb.Replace("&#39;", "\'");
            sb.Replace("&quot;", "\"");
            sb.Replace("&gt;", ">");
            sb.Replace("&lt;", "<");
            sb.Replace("&amp;", "&");


            return sb.ToString();
        }

        /// <summary>
        /// HtmlEncode
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string HtmlEncode(string content)
        {
            return HttpContext.Current.Server.HtmlEncode(content);
        }

        /// <summary>
        ///  HtmlDecode
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string HtmlDecode(string content)
        {
            return HttpContext.Current.Server.HtmlDecode(content);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(string str)
        {
            return HttpUtility.UrlDecode(str);
        }

        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIp(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
 

        /// <summary>
        /// 返回字符串真实长度, 1个汉字长度为2
        /// </summary>
        /// <returns></returns>
        public static int GetLength(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return 0;
            }
            return Encoding.Default.GetBytes(str).Length;
        }

        /// <summary>
        /// 编码成 sql 文本可以接受的格式
        /// </summary>
        public static string SqlEncode(string s)
        {
            return string.IsNullOrEmpty(s) ? string.Empty : s.Trim().Replace("'", "''");
        }

        /// <summary>
        /// 检测是否有Sql危险字符
        /// 没有返回true
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeSqlString(string str)
        {

            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }
 

        /// <summary>
        /// 从字符串的指定位置截取指定长度的子字符串(过时)
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <param name="length">子字符串的长度</param>
        /// <returns>子字符串</returns>
        public static string CutString(string str, int startIndex, int length)
        {
            return CutString(str, startIndex, length, string.Empty);
        }

        /// <summary>
        /// 从字符串的指定位置开始截取到字符串结尾的了符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="length">子字符串的起始位置</param>
        /// <returns>子字符串</returns>
        public static string CutString(string str, int length)
        {
            return CutString(str, 0, length, string.Empty);
        }

        /// <summary>
        /// 截取字符
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public static string CutString(string str, int length, string def)
        {
            return CutString(str, 0, length, def);
        }

        public static string CutString(string str, int startIndex, int length, string def)
        {
            if (startIndex >= 0)
            {
                if (length < 0)
                {
                    length = length * -1;
                    if (startIndex - length < 0)
                    {
                        length = startIndex;
                        startIndex = 0;
                    }
                    else
                    {
                        startIndex = startIndex - length;
                    }
                }


                if (startIndex > str.Length)
                {
                    return "";
                }


            }
            else
            {
                if (length < 0)
                {
                    return "";
                }
                else
                {
                    if (length + startIndex > 0)
                    {
                        length = length + startIndex;
                        startIndex = 0;
                    }
                    else
                    {
                        return "";
                    }
                }
            }

            if (str.Length - startIndex <= length)
            {
                length = str.Length - startIndex;
                def = string.Empty;
            }

            try
            {
                return str.Substring(startIndex, length) + def;
            }
            catch
            {
                return str + def;
            }
        }



        /// <summary>
        /// 移除Html标记
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveHtml(string content)
        {
            const string regexstr = @"<[^>]*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase).Trim();
        }

        /// <summary>
        ///  判断字符串是否合法的日期格式
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsData(string value)
        {
            try
            {
                System.DateTime.Parse(value);
            }
            catch
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 判断给定的字符串(strInt)是否是数值型
        /// </summary>
        /// <param name="strInt">要确认的字符串</param>
        /// <returns>是则返加true 不是则返回 false</returns>
        public static bool IsInt(string strInt)
        {
            return !string.IsNullOrEmpty(strInt) && new Regex(@"^(0|[1-9]\d*)$").IsMatch(strInt);
            //return new Regex(@"^([0-9])[0-9]*(\.\w*)?$").IsMatch(strInt);	//整数和小数
        }

        /// <summary>
        /// 是否为httpUrl地址
        /// </summary>
        /// <param name="httpUrl"></param>
        /// <returns></returns>
        public static bool IsHttpUrl(string httpUrl)
        {
            //return Regex.IsMatch(WebUrl, @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
            //    return Regex.IsMatch(WebUrl, @"http://");

            return httpUrl.IndexOf("http://") != -1;
        }
        /// <summary>
        /// 检测是否符合email格式
        /// </summary>
        /// <param name="strEmail">要判断的email字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsEmail(string strEmail)
        {
            return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        /// <summary>
        /// string型转换为int型,转换失败返回缺省值
        /// </summary>
        /// <param name="str">要转换的字符串</param>
        /// <param name="def">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static int StrToInt(string str, int def)
        {
            if (IsInt(str))
            {
                return int.Parse(str);
            }
            else
            {
                return def;
            }
        }


        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetMd5(string str)
        {
            if (str == null)
            {
                str = string.Empty;
            }
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");

        }
        /// <summary>
        /// 返回URL中结尾的文件名
        /// </summary>		
        public static string GetFileName(string url)
        {
            //	HttpContext.Current.Response.Write( url.IndexOf("?"));

            if (url == null)
            {
                return "";
            }
            //是否有参数
            if (url.IndexOf("?") != -1)
            {
                //去掉参数
                string noquery = url.Substring(0, url.IndexOf("?"));

                //根据/分组
                string[] filenames = noquery.Split(new char[] { '/' });

                //文件名
                string filename = filenames[filenames.Length - 1];

                return filename;
            }
            else
            {
                return System.IO.Path.GetFileName(url);
            }

            //以前的
            //			if (url == null)
            //			{
            //				return "";
            //			}
            //			string[] strs1 = url.Split(new char[]{'/'});
            //			return strs1[strs1.Length - 1].Split(new char[]{'?'})[0];
        }


        ///// <summary>
        ///// 生成随机码
        ///// </summary>
        ///// <param name="length">长度</param>
        ///// <param name="isLower">是否转化成小写</param>
        ///// <returns></returns>
        //public static string RandCode(int length, bool isLower)
        //{
        //    char[] arrChar = new char[]{
        //   'a','b','d','c','e','f','g','h','i','j','k','l','m','n','p','r','q','s','t','u','v','w','z','y','x',
        //   '0','1','2','3','4','5','6','7','8','9',
        //   'A','B','C','D','E','F','G','H','I','J','K','L','M','N','Q','P','R','T','S','V','U','W','X','Y','Z'
        //  };

        //    StringBuilder num = new StringBuilder();

        //    Random rnd = new Random(DateTime.Now.Millisecond);
        //    for (int i = 0; i < length; i++)
        //    {
        //        num.Append(arrChar[rnd.Next(0, arrChar.Length)].ToString());

        //    }
        //    if (isLower)
        //    {
        //        return num.ToString().ToLower();
        //    }
        //    return num.ToString();
        //}

        /// <summary>
        /// 将时间换成中文
        /// </summary>
        /// <param name="datetime">时间</param>
        /// <returns></returns>
        public static string DateToChineseString(DateTime datetime)
        {
            TimeSpan ts = DateTime.Now - datetime;
            //    System.Web.HttpContext.Current.Response.Write(ts.TotalDays);
            if ((int)ts.TotalDays >= 365)
            {
                return (int)ts.TotalDays / 365 + "年前";
            }
            if ((int)ts.TotalDays >= 30 && ts.TotalDays <= 365)
            {
                return (int)ts.TotalDays / 30 + "月前";
            }
            if ((int)ts.TotalDays == 1)
            {
                return "昨天";
            }
            if ((int)ts.TotalDays == 2)
            {
                return "前天";
            }
            if ((int)ts.TotalDays >= 3 && ts.TotalDays <= 30)
            {
                return (int)ts.TotalDays + "天前";
            }
            if ((int)ts.TotalDays == 0)
            {
                if ((int)ts.TotalHours != 0)
                {
                    return (int)ts.TotalHours + "小时前";
                }
                else
                {
                    if ((int)ts.TotalMinutes == 0)
                    {
                        return "1分钟前";
                    }
                    else
                    {
                        return (int)ts.TotalMinutes + "分钟前";
                    }
                }
            }
            return datetime.ToString("yyyy年MM月dd日 HH:mm");
        }

 

        public static int ObjectToInt(object expression)
        {
            return ObjectToInt(expression, 0);
        }

        /// <summary>
        /// 将对象转换为Int32类型
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        public static int ObjectToInt(object expression, int defValue)
        {
            if (expression != null)
                return StrToInt(expression.ToString(), defValue);

            return defValue;
        }


        public static List<string> GetStrArray(string str, char speater, bool toLower)
        {
            List<string> list = new List<string>();
            string[] ss = str.Split(speater);
            foreach (string s in ss)
            {
                if (!string.IsNullOrEmpty(s) && s != speater.ToString())
                {
                    string strVal = s;
                    if (toLower)
                    {
                        strVal = s.ToLower();
                    }
                    list.Add(strVal);
                }
            }
            return list;
        }

        /// <summary>
        /// 不重复的随机数
        /// </summary>
        /// <returns></returns>
        public static string GetRandNum(int num)
        {
            int x = 1000;
            int y = 9999;

            switch (num)
            {
                case 1:
                case 2:
                    x = 10;
                    y = 99;
                    break;
                case 3:
                    x = 100;
                    y = 999;
                    break;
                case 4:
                    x = 1000;
                    y = 9999;
                    break;
                case 5:
                    x = 10000;
                    y = 99999;
                    break;
                case 6:
                    x = 100000;
                    y = 999999;
                    break;
                case 7:
                    x = 1000000;
                    y = 9999999;
                    break;
                case 8:
                    x = 10000000;
                    y = 99999999;
                    break;
            }


            string ranName = string.Empty;
            Random random = new Random(Guid.NewGuid().GetHashCode());
            //ranName += DateTime.Now.ToString("yyyyMMddHHmmss");
            ranName += random.Next(x, y);
            return ranName;
        }

        /// <summary>
        /// 精确截取字符串 全角为2，半角为1， 按半角长度截取
        /// </summary>
        /// <param name="str"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string SubStrByByte(string str, int len)
        {

            int bytecount = Encoding.Default.GetByteCount(str);
            int sum = 0;
            if (bytecount > len)
            {
                for (int i = 0; i < len; i++)
                {
                    if (sum < len)
                    {
                        sum += Encoding.Default.GetByteCount(str[i].ToString());
                    }
                    else
                    {
                        if (sum % 2 == 0)
                        {
                            sum = i;
                        }
                        else
                        {
                            sum = i - 1;
                        }
                        break;
                    }
                }
                str = str.Substring(0, sum);
            }
            return str;
        }

        public static string[] GetStrArray(string str)
        {
            return str.Split(new char[',']);
        }
        public static string GetArrayStr(List<string> list, string speater)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.Count; i++)
            {
                if (i == list.Count - 1)
                {
                    sb.Append(list[i]);
                }
                else
                {
                    sb.Append(list[i]);
                    sb.Append(speater);
                }
            }
            return sb.ToString();
        }


        #region 删除最后一个字符之后的字符

        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }

        /// <summary>
        /// 删除最后结尾的指定字符后的字符
        /// </summary>
        public static string DelLastChar(string str, string strchar)
        {
            return str.Substring(0, str.LastIndexOf(strchar));
        }

        #endregion




        /// <summary>
        /// 转全角的函数(SBC case)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToSbc(string input)
        {
            //半角转全角：
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new string(c);
        }

        /// <summary>
        ///  转半角的函数(SBC case)
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns></returns>
        public static string ToDBC(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }

        public static List<string> GetSubStringList(string o_str, char sepeater)
        {
            List<string> list = new List<string>();
            string[] ss = o_str.Split(sepeater);
            foreach (string s in ss)
            {
                if (!string.IsNullOrEmpty(s) && s != sepeater.ToString())
                {
                    list.Add(s);
                }
            }
            return list;
        }


        #region 将字符串样式转换为纯字符串
        public static string GetCleanStyle(string StrList, string SplitString)
        {
            string RetrunValue = "";
            //如果为空，返回空值
            if (StrList == null)
            {
                RetrunValue = "";
            }
            else
            {
                //返回去掉分隔符
                string NewString = "";
                NewString = StrList.Replace(SplitString, "");
                RetrunValue = NewString;
            }
            return RetrunValue;
        }
        #endregion

        #region 将字符串转换为新样式
        public static string GetNewStyle(string StrList, string NewStyle, string SplitString, out string Error)
        {
            string ReturnValue = "";
            //如果输入空值，返回空，并给出错误提示
            if (StrList == null)
            {
                ReturnValue = "";
                Error = "请输入需要划分格式的字符串";
            }
            else
            {
                //检查传入的字符串长度和样式是否匹配,如果不匹配，则说明使用错误。给出错误信息并返回空值
                int strListLength = StrList.Length;
                int NewStyleLength = GetCleanStyle(NewStyle, SplitString).Length;
                if (strListLength != NewStyleLength)
                {
                    ReturnValue = "";
                    Error = "样式格式的长度与输入的字符长度不符，请重新输入";
                }
                else
                {
                    //检查新样式中分隔符的位置
                    string Lengstr = "";
                    for (int i = 0; i < NewStyle.Length; i++)
                    {
                        if (NewStyle.Substring(i, 1) == SplitString)
                        {
                            Lengstr = Lengstr + "," + i;
                        }
                    }
                    if (Lengstr != "")
                    {
                        Lengstr = Lengstr.Substring(1);
                    }
                    //将分隔符放在新样式中的位置
                    string[] str = Lengstr.Split(',');
                    foreach (string bb in str)
                    {
                        StrList = StrList.Insert(int.Parse(bb), SplitString);
                    }
                    //给出最后的结果
                    ReturnValue = StrList;
                    //因为是正常的输出，没有错误
                    Error = "";
                }
            }
            return ReturnValue;
        }
        #endregion

        //获取next
        public static int[] GetKmpNext(string pattern)
        {
            int[] next = new int[pattern.Length];
            next[0] = -1;
            if (pattern.Length < 2) return next;
            next[1] = 0;
            int i = 2, j = 0;
            while (i < pattern.Length)
            {
                if (pattern[i - 1] == pattern[j])
                {
                    next[i++] = ++j;
                }
                else
                {
                    j = next[j];
                    if (j == -1)
                    {
                        next[i++] = ++j;
                    }
                }
            }
            return next;
        }
        /// <summary>
        /// 查询关键字方法,传入源和关键字数组,多关键字数组中任意一个匹配即返回True
        /// </summary>
        /// <param name="source">原字符串</param>
        /// <param name="keywords">关键字列表用|分开</param>
        /// <returns>如果存在关键字返回true，反之返回false。</returns>
        public static bool SearchKeywords(string source, string[] keywords)
        {
            int wordCount = keywords.Length;
            int[][] nexts = new int[wordCount][];
            int i = 0;
            for (i = 0; i < wordCount; i++)
            {
                nexts[i] = GetKmpNext(keywords[i]);
            }
            i = 0;
            int[] j = new int[nexts.Length];
            while (i < source.Length)
            {
                for (int k = 0; k < wordCount; k++)
                {
                    if (source[i] == keywords[k][j[k]])
                    {
                        j[k]++;
                    }
                    else
                    {
                        j[k] = nexts[k][j[k]];
                        if (j[k] == -1)
                        {
                            j[k]++;
                        }
                    }
                    if (j[k] >= keywords[k].Length)
                    {
                        return true;
                    }
                }
                i++;
            }
            return false;
        }

        //public static string To

        /// <summary>
        /// Byte2s the string.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string ByteToString(byte[] value)
        {

            if (value == null)
                return null;

            MemoryStream stream = new MemoryStream(value);
            StreamReader reader = new StreamReader(stream);
            return reader.ReadToEnd();

        }

        public static string ByteToString(byte[] value, Encoding encoding)
        {

            if (value == null)
                return null;

            MemoryStream stream = new MemoryStream(value);
            StreamReader reader = new StreamReader(stream, encoding);
            return reader.ReadToEnd();

        }


        /// <summary>
        /// String2s the byte.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static byte[] StringToByte(string value)
        {

            if (value == null)
                return null;

            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);
            writer.Write(value);
            writer.Flush();
            return stream.ToArray();

        }

        public static byte[] StringToByte(string value, Encoding encoding)
        {

            if (value == null)
                return null;

            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream, encoding);
            writer.Write(value);
            writer.Flush();
            return stream.ToArray();

        }

        /// <summary>
        /// 返回十六进制代表的字符串
        /// </summary>
        /// <param name="mHex"></param>
        /// <returns></returns>
        public static string HexStringToString(string mHex)
        {
            mHex = mHex.Replace(" ", "");
            if (mHex.Length <= 0) return "";

            byte[] vBytes = new byte[mHex.Length / 2];
            for (int i = 0; i < mHex.Length; i += 2)
                if (!byte.TryParse(mHex.Substring(i, 2),
                    System.Globalization.NumberStyles.HexNumber, null, out vBytes[i / 2]))
                    vBytes[i / 2] = 0;

            return Encoding.Default.GetString(vBytes);
        }

        private static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        public static string ByteToHexString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length * 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                int b = bytes[i];
                chars[i * 2] = hexDigits[b >> 4];
                chars[i * 2 + 1] = hexDigits[b & 0xF];
            }
            return new string(chars);
        }

        public static string ByteToAsciiStrng(byte[] bytes)
        {
            StringBuilder builder = new StringBuilder();

            foreach (byte b in bytes)
            {
                if (b >= 32 && b <= 127)
                    builder.Append(System.Text.Encoding.UTF8.GetString(new byte[] { b }));
                else
                    builder.Append(".");
            }

            return builder.ToString();
        }

        /// <summary>
        /// 使用UTF8对byte解码，得到string
        /// </summary>
        /// <param name="characters">Unicode Byte Array to be converted to String</param>
        /// <returns>String converted from Unicode Byte Array</returns>
        public static string Utf8ByteToString(byte[] value)
        {

            if (value == null)
                return null;

            UTF8Encoding encoding = new UTF8Encoding();
            string constructedString = encoding.GetString(value);
            return (constructedString);

        }
        /// <summary>
        /// 使用UTF8对string编码，得到byte
        /// </summary>
        /// <param name="pXmlString"></param>
        /// <returns></returns>
        public static byte[] UTF8StringToByte(string value)
        {

            if (value == null)
                return null;

            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(value);
            return byteArray;

        }

        /// <summary>
        /// Dot2s the long IP.
        /// </summary>
        /// <param name="dotIP">The dot IP.</param>
        /// <returns></returns>
        public static long IPToLong(string dotIP)
        {

            string[] subIP = dotIP.Split('.');
            //IP Address = w.x.y.z 
            //IP Number = 16777216 * w + 65536 * x + 256 * y + z  
            long ip = 16777216 * Convert.ToInt64(subIP[0]) + 65536 * Convert.ToInt64(subIP[1]) + 256 * Convert.ToInt64(subIP[2]) + Convert.ToInt64(subIP[3]);
            return ip;

        }
        /// <summary>
        /// Longs the I p2 dot.
        /// </summary>
        /// <param name="longIP">The long IP.</param>
        /// <returns></returns>
        public static string LongToIp(long longIP)
        {

            string dotIP = "";
            int subIP = 0;

            long one = longIP / 16777216;
            subIP = Convert.ToInt32(one.ToString("f0")) % 256;
            dotIP = subIP.ToString() + ".";
            long two = longIP / 65536;
            subIP = Convert.ToInt32(two.ToString("f0")) % 256;
            dotIP += subIP.ToString() + ".";
            long three = longIP / 256;
            subIP = Convert.ToInt32(three.ToString("f0")) % 256;
            dotIP += subIP.ToString() + ".";
            long four = longIP % 256;
            subIP = Convert.ToInt32(four.ToString("f0"));
            dotIP += subIP.ToString();
            return dotIP;

        }
    }
}
